//获取基础域名：比如baidu.com
export const getBaseUrl = () => {
    const currentHost = window.location.host;
    if (currentHost.includes("localhost") || currentHost.includes("127.0.0.1")) {
        return "http://xadmin.cn" //使用开发域名
    }

    var currentProtocol = window.location.protocol;
    if (currentProtocol === "https:") {
        return `"https://${currentHost.trimEnd()}`;
    } else if (currentProtocol === "http:") {
        return `"http://${currentHost.trimEnd()}`;
    }
};

export const getBaseApi = () => {
    const currentHost = window.location.host;
    if (currentHost.includes("localhost") || currentHost.includes("127.0.0.1")) {
        return "http://xadmin.cn" //使用开发域名
    }

    return "";
};

//组装一个静态文件
//addTimestamp：是否加上时间戳(动态刷新用)
export const formatStaticUrl = (staticPath: string, addTimestamp = true) => {
    if (!staticPath) {
        return "";
    }
    if (staticPath.includes("/h5images")) {
        return staticPath
    }
    const currentHost = window.location.host;
    let baseUrl = ""
    if (currentHost.includes("localhost") || currentHost.includes("127.0.0.1")) {
        baseUrl = "http://xadmin.cn" //使用开发域名
    }

    // let baseUrl = getBaseUrl();
    //windows上传路径是 \\要先替换一下
    staticPath = staticPath.replaceAll("\\", "/")
    staticPath = removePrefix(staticPath);//删除 ./前缀
    var timestamp = Date.now(); // 获取当前时间的毫秒数
    let url = `${baseUrl}/${staticPath}`;
    if (addTimestamp) {
        url = url + "?" + timestamp;
    }
    return url;
};

//删除静态文件前缀
function removePrefix(str: string) {
    try {
        if (str.startsWith("./")) {
            return str.substring(2);
        } else if (str.startsWith("/")) {
            return str.substring(1);
        } else {
            return str;
        }
    } catch (e) {
        console.log(str, " ---str");
        console.log(e, " ---e");
        return "";
    }
    return "";
}

// 测试示例
// console.log(removePrefix("./example.txt")); // 输出 "example.txt"
// console.log(removePrefix("/example.txt")); // 输出 "example.txt"
// console.log(removePrefix("example.txt"));  // 输出 "example.txt"
